Page({

  // 下拉刷新
  onPullDownRefresh() {
    wx.showLoading({ title: '加载中...' });
    this.fetchOrders(() => {
      wx.stopPullDownRefresh();
      wx.hideLoading();
    });
  },
  data: {
    orders: [],
    pageNum: 1,
    pageSize: 10,
    total: 0,
    orderNo: '',
    isLoggedIn: false, // 添加登录状态字段
  },

  onLoad() {
    this.checkLoginStatus();
    // 监听登录成功事件
    this.bindLoginSuccessEvent();
  },

  onShow() {
    this.checkLoginStatus();
  },

  onUnload() {
    // 页面卸载时移除事件监听
    this.unbindLoginSuccessEvent();
  },

  // 绑定登录成功事件
  bindLoginSuccessEvent() {
    const eventBus = require('../../utils/eventBus');
    this.loginSuccessHandler = (userInfo) => {
      console.log('订单页面收到登录成功事件');
      this.setData({ isLoggedIn: true });
      this.fetchOrders();
    };
    eventBus.on('loginSuccess', this.loginSuccessHandler);
  },

  // 解绑登录成功事件
  unbindLoginSuccessEvent() {
    if (this.loginSuccessHandler) {
      const eventBus = require('../../utils/eventBus');
      eventBus.off('loginSuccess', this.loginSuccessHandler);
    }
  },

  // 处理其他页面登录成功的回调
  onLoginSuccess(userInfo) {
    console.log('订单页面收到登录成功通知');
    this.setData({ isLoggedIn: true });
    this.fetchOrders();
  },

  // 检查登录状态
  checkLoginStatus() {
    const app = getApp();
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    
    if (token && userInfo) {
      try {
        const parsedUserInfo = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo;
        if (parsedUserInfo && parsedUserInfo.id) {
          this.setData({ isLoggedIn: true });
          app.globalData.userInfo = parsedUserInfo;
          this.fetchOrders(); // 已登录则获取订单
          return;
        }
      } catch (error) {
        console.error('解析用户信息失败：', error);
      }
    }
    
    // 未登录状态
    this.setData({ 
      isLoggedIn: false,
      orders: []
    });
  },

  // 微信一键登录
  handleLogin() {
    wx.showLoading({ title: '登录中...', mask: true });

    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (profileRes) => {
        const basicUserInfo = profileRes.userInfo;

        wx.login({
          success: (loginRes) => {
            if (loginRes.code) {
              wx.request({
                url: 'https://visa.goldenholiday.com/api/miniapp/admin/user/wxLogin',
                method: 'POST',
                header: { 'content-type': 'application/json' },
                data: {
                  code: loginRes.code,
                  userInfo: {
                    nickName: basicUserInfo.nickName,
                    avatarUrl: basicUserInfo.avatarUrl
                  }
                },
                success: (res) => {
                  wx.hideLoading();
                  if (res.statusCode === 200 && res.data.code === 1) {
                    const backendUserInfo = res.data.data;

                    // 存储 Token
                    const token = backendUserInfo.token;
                    wx.setStorageSync('token', token);
                    getApp().globalData.token = token;

                    // 更新用户信息
                    wx.setStorageSync('userInfo', JSON.stringify(backendUserInfo));
                    getApp().globalData.userInfo = backendUserInfo;

                    // 更新页面状态
                    this.setData({ isLoggedIn: true });

                    // 获取订单数据
                    this.fetchOrders();

                    // 使用事件总线通知其他页面登录成功
                    const eventBus = require('../../utils/eventBus');
                    eventBus.emit('loginSuccess', backendUserInfo);

                    if (!backendUserInfo.phone) {
                      wx.showToast({
                        title: '登录成功，请绑定手机号',
                        icon: 'none',
                        duration: 2000
                      });
                    } else {
                      wx.showToast({ title: '登录成功', icon: 'success' });
                    }
                  } else {
                    wx.showToast({ title: res.data.msg || '登录失败', icon: 'none' });
                  }
                },
                fail: (err) => {
                  wx.hideLoading();
                  console.error('登录请求失败：', err);
                  wx.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
                }
              });
            } else {
              wx.hideLoading();
              wx.showToast({ title: '获取登录凭证失败', icon: 'none' });
            }
          },
          fail: (err) => {
            wx.hideLoading();
            console.error('wx.login 失败:', err);
            wx.showToast({ title: '微信登录调用失败', icon: 'none' });
          }
        });
      },
      fail: (err) => {
        wx.hideLoading();
        if (err.errMsg.includes('fail auth deny')) {
          console.log('用户拒绝授权用户信息');
          wx.showToast({ title: '您取消了授权', icon: 'none' });
        } else {
          console.error('获取用户信息失败:', err);
          wx.showToast({ title: '获取用户信息失败', icon: 'none' });
        }
      }
    });
  },



  handleRefund(e) {
    const order = e.currentTarget.dataset.order;
    wx.showModal({
      title: '确认退款',
      content: '您确定要申请退款吗？',
      success: (res) => {
        if (res.confirm) {
          const requestData = { 
            orderId: order.orderNumber, // 提供订单ID
            refundAmount: order.amount, // 提供退款金额
            refundReason: '用户申请退款' // 提供退款原因
          };
  
          // 输出调试信息
          console.log('提交给后端的退款请求数据:', JSON.stringify(requestData));
  
          // 调用退款接口
          wx.request({
            url: 'https://visa.goldenholiday.com/api/miniapp/admin/pay/refund',
            method: 'POST',
            header: { 'content-type': 'application/json', 'token': wx.getStorageSync('token') },
            data: requestData,
            success: (res) => {
              if (res.data.code === 1) {
                wx.showToast({ title: '退款申请成功', icon: 'success' });
                this.fetchOrders(); // 刷新订单数据
              } else {
                wx.showToast({ title: '退款申请失败', icon: 'none' });
              }
            }
          });
        }
      }
    });
  },

  fetchOrders(callback) {
    // 检查登录状态
    if (!this.data.isLoggedIn) {
      if (typeof callback === 'function') callback();
      return;
    }

    const app = getApp();
    wx.request({
      url: 'https://visa.goldenholiday.com/api/miniapp/admin/order/pageinfo',
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: {
        userId: app.globalData.userInfo.id,
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const orders = res.data.data.records.map(order => ({
            id: order.id, // 增加订单ID字段
            orderNumber: order.number,
            orderNo: order.number,
            info: order.productName,
            person: order.contactPerson,
            status: order.orderStatus,
            orderStatu: order.orderStatus,
            statusClass: this.getStatusClass(order.orderStatus),
            actionText: this.getActionText(order.orderStatus),
            amount: order.mount || order.orderAmount
          }));

          this.setData({
            orders,
            total: res.data.data.total
          });
        }
        if (typeof callback === 'function') callback();
      },
      fail: () => {
        if (typeof callback === 'function') callback();
      }
    });
  },

  getStatusClass(orderStatus) {
    switch (orderStatus) {
      case '待支付': return 'pending';
      case '已支付': return 'paid';
      case '已完成': return 'completed';
      case '已退款': return 'refunded';
      case '待退款': return 'waiting-refund';
      default: return '';
    }
  },

  getActionText(orderStatus) {
    switch (orderStatus) {
      case '待支付': return '现在支付';
      case '已支付': return '查看详情';
      case '已完成': return '查看详情';
      case '已退款': return '查看详情';
      case '待退款': return '查看详情';
      default: return '查看详情';
    }
  },

  // 处理查看详情
  handleViewDetail(e) {
    const order = e.currentTarget.dataset.order;
    // 先显示加载中
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    
    // 延迟1秒后显示成功提示
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '已支付',
        icon: 'success',
        duration: 2000
      });
    }, 1000);
  },

  // 原有的 handleAction 函数保持不变，处理其他按钮操作
  handleAction(e) {
    const { index } = e.currentTarget.dataset;
    const order = this.data.orders[index];
    
    if (order.status === '待支付') {
      // 只在PC端弹窗温馨提示
      const platform = wx.getSystemInfoSync().platform;
      if (platform === 'windows' || platform === 'mac' || platform === 'linux') {
        wx.showModal({
          title: '温馨提示',
          content: '扫码支付后，请耐心等待系统响应，切勿着急点击“取消”按钮。如已支付，请务必等待页面自动跳转或提示后再操作。',
          showCancel: false,
          confirmText: '我知道了',
          success: () => {
            this.processPayment(order.orderNumber);
          }
        });
      } else {
        this.processPayment(order.orderNumber);
      }
    } else if (order.status === '已取消') {
      this.deleteOrder(order.orderNumber);
    } else {
      wx.navigateTo({
        url: `/pages/orderDetail/orderDetail?orderNo=${order.orderNumber}`
      });
    }
  },

  async processPayment(orderNo) {
    const app = getApp();
    try {
      const order = this.data.orders.find(o => o.orderNumber === orderNo);
      if (!order) {
        throw new Error('订单未找到');
      }
  
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: 'https://visa.goldenholiday.com/api/miniapp/admin/pay/payment',
          method: 'POST',
          header: { 'content-type': 'application/json', 'token': wx.getStorageSync('token') },
          data: { 
            orderId: order.orderNumber, // 传递订单号字符串
            userId: app.globalData.userInfo.id,
            total_fee: order.amount // 确保传递支付金额
          },
          success: resolve,
          fail: reject
        });
      });
      if (res.statusCode === 200 && res.data.code === 1) {
        const payData = res.data.data;
        await new Promise((resolve, reject) => {
          wx.requestPayment({
            timeStamp: payData.timeStamp,
            nonceStr: payData.nonceStr,
            package: payData.package,
            signType: payData.signType,
            paySign: payData.paySign,
            success: async () => {
              console.log('支付成功，更新订单状态为已支付');
              await this.updateOrderStatus(orderNo, '已支付');
              wx.showToast({ title: '支付成功', icon: 'success' });
              this.fetchOrders(); // 刷新订单数据
            },
            fail: async (err) => {
              console.log('支付失败或取消:', err);
              await this.updateOrderStatus(orderNo, '待支付');
              if (err.errMsg === 'requestPayment:fail cancel') {
                wx.showToast({ title: '支付已取消', icon: 'none' });
              } else {
                wx.showToast({ title: '支付失败', icon: 'none' });
              }
            }
          });
        });
      } else {
        throw new Error(res.data.msg || '获取支付参数失败');
      }
    } catch (err) {
      console.error('支付处理错误:', err);
      wx.showToast({ title: '支付处理失败', icon: 'none' });
    }
  },
  
  async updateOrderStatus(orderNo, orderStatus) {
    try {
      console.log(`更新订单状态: orderNo=${orderNo}, orderStatus=${orderStatus}`);
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: 'https://visa.goldenholiday.com/api/miniapp/admin/order/updateStatus',
          method: 'POST',
          header: { 'content-type': 'application/json', 'token': wx.getStorageSync('token') },
          data: { orderNo, orderStatus },
          success: resolve,
          fail: (error) => {
            console.error('请求失败:', error);
            reject(error);
          }
        });
      });
  
      if (res.data.code !== 1) {
        console.error('更新订单状态失败:', res.data.msg);
        throw new Error(res.data.msg || '更新订单状态失败');
      } else {
        console.log('订单状态更新成功');
      }
    } catch (error) {
      console.error('更新订单状态错误:', error);
    }
  }
});
